<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>检测页面</title>
    <link href="https://chongzhi.nthink.cn/static/css/tailwind.min.css" rel="stylesheet">
    <script src="https://chongzhi.nthink.cn/static/js/jquery-3.6.0.min.js"></script>
    <link rel="stylesheet" href="https://chongzhi.nthink.cn/static/layUi/css/layui.css" media="all">
    <script src="https://chongzhi.nthink.cn/static/layUi/layui.js"></script>
    <style>
        body {
            background-color: #f9fafb; /* 灰色背景 */
        }
    </style>
</head>
<body class="flex items-center justify-center h-screen">

    <div class="bg-white rounded-lg shadow-lg p-6 w-11/12 max-w-md">
        <input type="hidden" name="code" id="code" value="${code}"/>
        <input type="hidden" name="userName" id="userName" value="${userName}"/>
        <input type="hidden" name="mobile" id="mobile" value="${mobile}"/>
        <input type="hidden" name="userType" id="userType" value="${type}"/>
        <input type="hidden" name="equityCode" id="equityCode" value="${equityCode}"/>
        <h2 class="text-center text-xl font-bold mb-4">操作说明</h2>
        <div class="border border-red-500 bg-red-100 text-red-700 p-4 rounded-lg mb-4">
            <p>1. 请点击下方“开始检测”按钮；</p>
            <p>2. 请张口并吐出舌头，放置在屏幕中间；</p>
            <p>3. 拍照后即可自动进行检测。</p>
        </div>

        <div class="bg-blue-100 rounded-lg shadow-lg p-6 max-w-md" style="margin-top: 20px;     margin-bottom: 25px;" id="template">
            <div class="flex justify-center mb-4">
                <img id="output2" src="https://chongzhi.nthink.cn/static/tongue/tongueTemplate.png" alt="检测图片" class="rounded-full w-24 h-24 object-cover">
            </div>
            <h2 class="text-xl font-bold mb-4">拍照提示：</h2>
            <p class="text-blue-800" id="desc2">嘴巴张大，露出舌根，舌头尽量伸长，舌尖自然向下，避免伸舌事件过长、过于用力。</p>
        </div>

        <input type="file" accept="image/*" id="file-input" capture="camera" class="hidden">
        <button id="capture-btn" class="w-full bg-green-500 text-white py-2 rounded-lg hover:bg-green-600">
            开始检测
        </button>
        <canvas id="canvas" class="hidden"></canvas>

        <div class="bg-blue-100 rounded-lg shadow-lg p-6 max-w-md" style="margin-top: 20px; display: none;" id="content">
            <div class="flex justify-center mb-4">
                <img id="output" src="" alt="检测图片" class="rounded-full w-24 h-24 object-cover">
            </div>
            <h2 class="text-xl font-bold mb-4">检测报告：</h2>
            <div class="flex justify-between mb-4">
                <div>
                    <span class="text-gray-600">舌色</span><br>
                    <span class="font-semibold" id="tongue"></span>
                </div>
                <div class="border-l-2 border-gray-300 mx-4"></div>
                <div>
                    <span class="text-gray-600">舌型</span><br>
                    <span class="font-semibold" id="coating"></span>
                </div>
            </div>
            <p class="text-blue-800" id="desc"></p>
        </div>

    </div>

    <script>
        const captureButton = document.getElementById('capture-btn');
        const fileInput = document.getElementById('file-input');
        const canvas = document.getElementById('canvas');
        const context = canvas.getContext('2d');
        let gatherId = "";
        const mobile = $("#mobile").val();
        
        $(document).ready(function() {
            fetch('https://chongzhi.nthink.cn/jkkc/api/v1/gh/init?mobile=' + mobile, {
                method: 'POST',
                headers: {
                    'apiId': '705k7d1d29',
                    'apiSalt': '654321',
                    'apiSign': '48efffa49fe877b4ae3f41f069354d4c'
                }
            }).then(response => response.json())
            .then(data => {
                gatherId = data.data.gatherId;
                console.log('Success:', data.data.gatherId);
            })
            .catch((error) => {
                console.error('Initialization Error:', error);
                alert("初始化失败，请稍后重试。");
            });
        });

        captureButton.addEventListener('click', () => {
            fileInput.click(); // 触发文件输入
        });

        fileInput.addEventListener('change', () => {
            const file = fileInput.files[0];
            if (file) {
                if (!file.type.startsWith('image/')) {
                    alert('请上传图片文件');
                    return;
                }

                const reader = new FileReader();
                reader.onload = function(e) {
                    const img = new Image();
                    img.onload = function() {
                        // Resize the image if it's too large
                        const maxWidth = 750;
                        const scaleFactor = Math.min(maxWidth / img.width, 1);
                        
                        canvas.width = img.width * scaleFactor;
                        canvas.height = img.height * scaleFactor;
                        
                        context.drawImage(img, 0, 0, canvas.width, canvas.height);

                        try {
                            const imageData = canvas.toDataURL('image/png');
                            const base64Data = imageData.replace(/^data:image\/png;base64,/, '');
                            document.getElementById('output').src = imageData;

                            let loading1 = layer.msg('数据采集中', {
                                icon: 16,
                                shade: 0.3,
                                time: 0
                            });

                            $.ajax({
                                url: 'https://chongzhi.nthink.cn/jkkc/api/v1/gh/tongue',
                                type: 'POST',
                                async: true,
                                data: {
                                    image: base64Data,
                                    mobile: mobile,
                                    gatherId: gatherId
                                },
                                headers: {
                                    'Content-Type': 'application/x-www-form-urlencoded',
                                    'apiId': '87953d1d29',
                                    'apiSalt': '654321',
                                    'apiSign': '0a33208e2dab82f1ccc8f80ac89c6b4a'
                                },
                                success: function(data) {
                                    console.log('Success:', data);
                                    layer.closeAll();
                                    if (data.code !== '0') {
                                        layui.layer.confirm('数据采集失败，请重试', {
                                            time: 20000, // 20s后自动关闭
                                            btn: ['重新采集'],
                                            yes: function(index, layero) {
                                                window.location.reload();
                                            },
                                            cancel: function() {
                                                window.location.reload();
                                            }
                                        });
                                    } else {
                                        $("#content").show();
                                        $("#template").hide();
                                        $("#coating").html(data.data.coating);
                                        $("#tongue").html(data.data.tongue);
                                        $("#desc").html(data.data.desc);
                                        $.ajax({
                                            type: "post",
                                            url: '${pageContext.request.contextPath}/mx/tongue/save',
                                            data: 'code=' + $("#code").val() + '&userName=' + $("#userName").val() + '&mobile=' + $("#mobile").val() + '&userType=' + $("#userType").val()
                                                + '&equityCode=' + $('#equityCode').val() + '&coating=' + data.data.coating + '&tongue=' + data.data.tongue,
                                            contentType: "application/x-www-form-urlencoded;charset=utf-8",
                                            success: function (data) {
                                                console.log("上传成功")
                                            },
                                            error: function (re, e, ex) {
                                                console.log("上传失败")
                                            },
                                        });
                                    }
                                },
                                error: function(xhr, status, error) {
                                    console.error('Processing Error:', error);
                                    layer.closeAll();
                                    alert("图片处理失败，请重试");
                                }
                            });
                        } catch (error) {
                            console.error('Canvas processing error:', error);
                            alert("画布处理失败，请重试");
                        }
                    };
                    img.src = e.target.result;
                    $("#capture-btn").hide()
                };
                reader.readAsDataURL(file);
            }
        });

    </script>
</body>
</html>
